# -*- coding: utf-8 -*-

# Define here the models for your spider middleware
#
# See documentation in:
# https://doc.scrapy.org/en/latest/topics/spider-middleware.html

from scrapy import signals
import requests
import re
import urllib3
import time


class DoubanSpiderMiddleware(object):
    # Not all methods need to be defined. If a method is not defined,
    # scrapy acts as if the spider middleware does not modify the
    # passed objects.

    @classmethod
    def from_crawler(cls, crawler):
        # This method is used by Scrapy to create your spiders.
        s = cls()
        crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
        return s

    def process_spider_input(self, response, spider):
        # Called for each response that goes through the spider
        # middleware and into the spider.

        # Should return None or raise an exception.
        return None

    def process_spider_output(self, response, result, spider):
        # Called with the results returned from the Spider, after
        # it has processed the response.

        # Must return an iterable of Request, dict or Item objects.
        for i in result:
            yield i

    def process_spider_exception(self, response, exception, spider):
        # Called when a spider or process_spider_input() method
        # (from other spider middleware) raises an exception.

        # Should return either None or an iterable of Response, dict
        # or Item objects.
        pass

    def process_start_requests(self, start_requests, spider):
        # Called with the start requests of the spider, and works
        # similarly to the process_spider_output() method, except
        # that it doesn’t have a response associated.

        # Must return only requests (not items).
        for r in start_requests:
            yield r

    def spider_opened(self, spider):
        spider.logger.info('Spider opened: %s' % spider.name)


class DoubanDownloaderMiddleware(object):
    # Not all methods need to be defined. If a method is not defined,
    # scrapy acts as if the downloader middleware does not modify the
    # passed objects.

    @classmethod
    def from_crawler(cls, crawler):
        # This method is used by Scrapy to create your spiders.
        s = cls()
        crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
        return s

    def process_request(self, request, spider):
        # Called for each request that goes through the downloader
        # middleware.

        # Must either:
        # - return None: continue processing this request
        # - or return a Response object
        # - or return a Request object
        # - or raise IgnoreRequest: process_exception() methods of
        #   installed downloader middleware will be called
        return None

    def process_response(self, request, response, spider):
        # Called with the response returned from the downloader.

        # Must either;
        # - return a Response object
        # - return a Request object
        # - or raise IgnoreRequest
        return response

    def process_exception(self, request, exception, spider):
        # Called when a download handler or a process_request()
        # (from other downloader middleware) raises an exception.

        # Must either:
        # - return None: continue processing this exception
        # - return a Response object: stops process_exception() chain
        # - return a Request object: stops process_exception() chain
        pass

    def spider_opened(self, spider):
        spider.logger.info('Spider opened: %s' % spider.name)


class ProxyMiddleware(object):
    def process_request(self, request, spider):
        """
        TODO 代理获取函数
        :param request:
        :param spider:
        """
        try:
            print("-----------------------------------------proxy start-----------------------------------------------------")
            print(request.meta)
            if "proxy" in request.meta.keys():
                print("old proxy")
            else:
                print("new proxy")
                # 设置接口默认值
                proxy_api = "http://http.tiqu.alicdns.com/getip3?num=1&type=2&pro=110000&city=110105&yys=100026&port=1&time=1&ts=1&ys=1&cs=1&lb=1&sb=0&pb=4&mr=2&regions=&gm=4"
                proxy_api_white = "http://wapi.http.cnapi.cc/index/index/save_white?neek=86575&appkey=88428b25888a8c9da847df07ab51d721&white={}"

                # 禁止https错误
                urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

                # 获取代理
                proxies = False
                req = requests.get(proxy_api, verify=False, timeout=30, proxies=proxies)
                res_json = req.json()
                print(res_json)
                # 是否未加入白名单
                if res_json['code'] == 113:
                    res = re.findall(r'\d+.\d+.\d+.\d+', res_json['msg'])
                    if res:
                        ip = res[0]
                        requests.get(proxy_api_white.format(ip))

                        request = requests.get(proxy_api, verify=False, timeout=30, proxies=proxies)
                        res_json = req.json()

                # 其他错误信息
                if res_json['code'] == 0:
                    request.meta['proxy'] = "http://" + res_json['data'][0]['ip'] + ":" + str(res_json['data'][0]['port'])
                else:
                    request.meta['proxy'] = "http://127.0.0.1:8081"

            print(request.meta)
            print("-----------------------------------------proxy end-----------------------------------------------------")
        except Exception as err:
            request.meta['proxy'] = 'http://127.0.0.1:8081'